import React, {
  useState,
  useEffect,
  useMemo,
  useImperativeHandle,
  forwardRef,
  Ref,
} from "react";
import {
  Table,
  TableProps,
  Pagination,
  Input,
  Button,
  Space,
  Spin,
  Checkbox,
  Drawer,
  Tooltip,
  message,
  Divider,
  Tag,
} from "antd";
import {
  SearchOutlined,
  ReloadOutlined,
  SettingOutlined,
  Loading3QuartersOutlined,
} from "@ant-design/icons";
import type {
  SorterResult,
  FilterValue,
  ColumnType,
} from "antd/es/table/interface";
import { TableAction } from "@/types/public";
import { ArrayToTree } from "@/common/common";

type TableRowSelection<T extends object = object> =
  TableProps<T>["rowSelection"];

export interface ProTableRef {
  refresh: () => void;
  getData: () => void;
  setData: (recodes: any) => void;
  getSelectedRowKeys: () => React.Key[];
}

// 定义泛型类型
type DataType = Record<string, any>;

interface ProTableProps<T extends DataType> {
  request: (params: {
    pageNum: number;
    pageSize: number;
    sorter?: SorterResult<T>;
    filters?: Record<string, FilterValue | null>;
    keyword?: string;
  }) => Promise<{ data: T[]; total: number }>;
  columns: any[];
  isTree?: boolean;
  rowKey?: string | ((record: T) => string);
  searchable?: boolean;
  slotProps?: Record<string, (record: T, index: number) => React.ReactNode>;
  sticky?: boolean; // 固定表头
  resizable?: boolean; // 启用列宽拖拽
  debounceWait?: number; // 👈 添加 debounceWait 可选属性
  tableAction?: TableAction<T>;
}
type Pagination = {
  pageNum: number;
  pageSize: number;
  total: number;
};
// 修改组件定义，明确保留泛型
function ProTable<T extends DataType>(
  props: ProTableProps<T>,
  ref: React.Ref<ProTableRef>
) {
  // 组件内部实现保持不变，除了以下这一行需要修改
  const [pagination, setPagination] = useState<Pagination>({
    pageNum: 1,
    pageSize: 10,
    total: 0,
  });

  const {
    request,
    columns,
    rowKey = "id",
    searchable = true,
    slotProps = {},
    sticky = true,
    resizable = true,
    debounceWait = 500,
    tableAction,
    isTree,
  } = props;

  // 状态管理
  const [data, setData] = useState<T[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectRowsKeys, setSelectRowsKeys] = useState<React.Key[]>([]);
  //定义刷新
  const [refresh, setRefresh] = useState(0);
  const [sorter, setSorter] = useState<SorterResult<T>>({});
  const [filters, setFilters] = useState<Record<string, FilterValue | null>>(
    {}
  );
  const [pageKeyword, setPageKeyword] = useState("");
  const [keyword, setKeyword] = useState("");
  const [visibleColumns, setVisibleColumns] = useState(() =>
    columns.map((col) => ({ ...col, visible: col.visible ?? true }))
  );

  useEffect(() => {
    setVisibleColumns(
      columns.map((col) => ({ ...col, visible: col.visible ?? true }))
    );
  }, [columns]);

  const [settingsOpen, setSettingsOpen] = useState(false);

  // 👇 暴露方法给父组件使用
  useImperativeHandle(ref, () => ({
    refresh: () => {
      setRefresh(refresh + 1);
    },
    getData: () => {
      return data;
    },
    setData: (data: T[]) => {
      setData(data);
    },
    getSelectedRowKeys: () => selectRowsKeys,
  }));

  useEffect(() => {
    setLoading(true);
    try {
      request({ ...pagination, keyword }).then((res: any) => {
        setPagination({
          ...pagination,
          total: res.total,
        });
        //如何取 props 的isTress？
        let resultData: T[] = res.items;

        if (isTree) {
          const treeData = ArrayToTree(res.items, {}) as unknown as T[];
          resultData = treeData;
        }

        setData(resultData);
      });
    } catch (e) {
      message.error("数据加载错误");
      console.error("数据加载错误", e);
    } finally {
      setLoading(false);
    }
  }, [pagination.pageNum, pagination.pageSize, keyword, refresh]);
  // 🔽 核心修改1：处理固定列和插槽列
  const processedColumns = useMemo(() => {
    const filteredCols = visibleColumns.filter((col) => col.visible);
    return filteredCols.map((col) => {
      // 插槽列处理
      if (col.slotName && slotProps[col.slotName]) {
        return {
          ...col,
          render: (_: any, record: T, index: number) =>
            slotProps[col.slotName!](record, index),
        };
      }
      return col;
    });
  }, [visibleColumns, slotProps]);

  // 🔽 核心修改3：固定表头配置
  const scrollConfig = useMemo(
    () => ({
      y: sticky ? "calc(100vh - 300px)" : undefined, // 动态计算高度
    }),
    [sticky]
  );

  // 列配置弹窗
  const renderColumnSettings = () => (
    <Drawer
      title="列设置"
      open={settingsOpen}
      onClose={() => setSettingsOpen(false)}
      maskClosable
    >
      <Space direction="vertical" style={{ width: "100%" }}>
        {visibleColumns.map((col) => (
          <Checkbox
            key={col.key?.toString() || col.dataIndex?.toString()}
            checked={col.visible}
            onChange={(e) => {
              const newCols = [...visibleColumns];
              const index = newCols.findIndex(
                (c) => c.key === col.key || c.dataIndex === col.dataIndex
              );
              if (index > -1) {
                newCols[index].visible = e.target.checked;
                setVisibleColumns(newCols);
              }
            }}
          >
            {typeof col.title === "function" ? col.title({}) : col.title}
          </Checkbox>
        ))}
      </Space>
    </Drawer>
  );

  function handlePaginationChange(pageNum: number, pageSize: number): void {
    setPagination({
      ...pagination,
      pageNum: pageNum,
      pageSize: pageSize,
    });
  }

  const rowSelection: TableRowSelection<T> = {
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectRowsKeys(selectedRowKeys);
    },
  };

  return (
    <div className="pro-table-container">
      {/* 顶部操作栏 */}
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          marginBottom: 16,
        }}
      >
        {searchable && (
          <Space>
            <Space.Compact style={{ width: "100%" }}>
              <Input
                value={pageKeyword}
                onChange={(e) => setPageKeyword(e.target.value)}
                placeholder="输入关键词搜索"
              />
              <Button
                type="primary"
                onClick={() => {
                  setPagination({
                    ...pagination,
                    pageNum: 1,
                  });
                  setKeyword(pageKeyword);
                }}
                icon={<SearchOutlined />}
              >
                搜索
              </Button>
            </Space.Compact>
            <Button
              onClick={() => {
                setPagination({
                  ...pagination,
                  pageNum: 1,
                });
                setPageKeyword("");
                setKeyword("");
              }}
              icon={<ReloadOutlined />}
            >
              重置
            </Button>
          </Space>
        )}
        <Space>
          <Space>
            <Button type="primary" onClick={tableAction?.add}>
              新增
            </Button>

            <Button
              type="primary"
              danger
              onClick={() => {
                if (tableAction?.delete) {
                  tableAction.delete(selectRowsKeys as any[]);
                }
              }}
            >
              删除
            </Button>
            <Button onClick={() => tableAction?.migrate?.()}>导出</Button>
          </Space>
          <Divider type="vertical" />

          <Tooltip title="列设置">
            <Button
              icon={<SettingOutlined />}
              onClick={() => setSettingsOpen(true)}
            />
          </Tooltip>
          <Tooltip title="刷新">
            <Button
              onClick={() => setRefresh(refresh + 1)}
              shape="circle"
              icon={<Loading3QuartersOutlined />}
            />
          </Tooltip>
        </Space>
      </div>

      {/* 表格主体 */}
      <Table<T>
        rowKey={rowKey}
        rowSelection={{ ...rowSelection }}
        columns={processedColumns}
        dataSource={data}
        loading={loading}
        pagination={false}
        scroll={scrollConfig}
        sticky={sticky}
      />
      {/* 分页器 */}
      <Pagination
        style={{ marginTop: 16, textAlign: "right" }}
        current={pagination.pageNum}
        pageSize={pagination.pageSize}
        total={pagination.total}
        onChange={handlePaginationChange}
        showSizeChanger
        showQuickJumper
        showTotal={(total) => `共 ${total} 条记录`}
      />

      {renderColumnSettings()}
    </div>
  );
}

// 正确的泛型导出方式
export default React.forwardRef(ProTable) as <T extends DataType>(
  props: ProTableProps<T> & { ref?: React.Ref<ProTableRef> }
) => ReturnType<typeof ProTable>;
